# encoding:utf-8
import random
import sys
from django.shortcuts import HttpResponse
import json
from IR.Util.Variables import Constant
from IR.Util.DB import DB
from  IR.moduels.snippet import Snippet
from  IR.moduels.Indexing import Search
from IR.moduels.HotRecommended import HotRecommended
import Util
reload(sys)
sys.setdefaultencoding('utf8')


def recommend(request):
    if (request.method == "POST"):
        #pagenum从0开始
        page_num = int(request.POST.get(Constant.PAGE_NUM, 0))
        count = int(request.POST.get(Constant.COUNT, 20))
        sort_mode = int(request.POST.get(Constant.SORT_MODE, 0))
        result = dict()
        res_list=None
        try:
            H = HotRecommended()
            # 此为对网易新闻热点的返回
            table = 'wangyi_news'
            res_list = list(H.hot_recommended(table))
        except Exception,e:
            print (e.message)
        if (res_list != None and len(res_list)>0):
            begin=page_num*count
            end=begin+count
            if(end>len(res_list)):
                end=len(res_list)
            news_list=list()
            for i in range(begin, end):
                news=dict()
                news["relativity"] = ""  # 相关度
                time = str(res_list[i][i]["news_pub_time"]).replace('/', '-')
                time = time[6:10] + "-" + time[:5] + " " + time[10:]
                news["time"] = time
                news["content"] = res_list[i]["news_content"]  # 内容
                news["title"] = res_list[i]["news_title"]  # 标题
                news["keywords"] = res_list[i]["news_keyword"]  # 关键词
                news["comment_num"] = res_list[i]["news_comment_num"]  # 评论数
                news["url"] = res_list[i]["news_url"]  # 网页链接
                news["source"] = res_list[i]["news_source_website"]
                snippet = Snippet()
                 # 生成预览
                IDs = list()
                IDs.append(res_list[i]["news_id"])
                preview = snippet.create_preview(IDs)
                news["preview"] = preview  # 预览
                news["commendatory_num"] = "暂无"  # 褒义评论数
                news["snippet"] =  ""
                news["relativity_news"] = "暂无"  # 相关新
                news_list.append(news)
            news_list = Util.sort_news(news_list, sort_mode)
            result[Constant.STATUS] = Constant.SUCCESS
            result[Constant.NWES_LIST] =news_list
            return HttpResponse(json.dumps(result), content_type="application/json")
        else:
            result[Constant.STATUS] = Constant.FAIL
            result[Constant.ERROR_CODE] = 3
            result[Constant.ERROR_MESSAGE] = "fail to get recommend data"
            return HttpResponse(json.dumps(result), content_type="application/json")